package managers;

import br.com.caelum.vraptor.ioc.Component;
import entities.UsersEntity;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;


@Component
public class UserManager {
    private final Session hibernateSession;

    public UserManager(Session hibernateSession) {
        this.hibernateSession = hibernateSession;
    }

    public UsersEntity createNewUser(String username, String email, String password) {
        UsersEntity user = new UsersEntity();
        user.setUserName(username);
        user.setEmail(email);
        user.setPassword(password);

        Transaction tx = hibernateSession.beginTransaction();
        hibernateSession.saveOrUpdate(user);
        tx.commit();

        return user;
    }

    public boolean checkUserExists(String username){
        /*Query query = hibernateSession.createQuery("FROM UsersEntity u WHERE u.userName = :username");
        query.setParameter("username", username);

        Transaction tx = hibernateSession.beginTransaction();
        List users = query.list();
        tx.commit();

        if(!users.isEmpty()){
            return true;
        }*/
        return getUsersData(username) != null;
    }

    public UsersEntity getUsersData(String username){
        Query query = hibernateSession.createQuery("FROM UsersEntity u WHERE u.userName = :username");
        query.setParameter("username", username);

        Transaction tx = hibernateSession.beginTransaction();
        UsersEntity user = (UsersEntity)query.uniqueResult();
        tx.commit();

        return user;
    }
}

